package reflect

import kotlin.reflect.KProperty
import kotlin.reflect.full.memberFunctions
import kotlin.reflect.full.memberProperties

object Mapper {
    fun <A : Any> toMap(a: A) = run {
        //获取A中所有的属性
        a::class.memberProperties.map { m ->
            val p = m as KProperty<*>
            p.name to p.call(a)
        }.toMap()
    }
}

fun main() {
    //使用反射把data类转换为map对象
    val map = Mapper.toMap(Person(name = "zhang", age = 30, sex = "man"))
//    println(map["name"])
//
//    println(Person::class.simpleName)

    //members可以把类的所有属性拿过来,包括成员变量和方法
    println("打印所有成员属性:")
    Person::class.members.forEach { println(it.name) }
    println("打印成员变量:")
    Person::class.memberProperties.forEach { println(it.name) }
    println("打印成员方法:")
    Person::class.memberFunctions.forEach { println(it.name) }
}